home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_01 / allison / deal.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-02  |  1.5 KB  |  59 lines

  1. LISTING 9 - A card shuffling program that illustrates the random number and
  2. integer division functions in <stdlib.h>
  3.  
  4. /* deal.c:  Deal a hand from a shuffled deck of cards */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <time.h>
  9.  
  10. #define DECKSIZE 52
  11. #define SUITSIZE 13
  12.  
  13. main(int argc, char *argv[])
  14. {
  15.     int ncards = DECKSIZE;   /* Deal full deck by default */
  16.     char deck[DECKSIZE];     /* An array of small integers */
  17.     size_t deckp;
  18.     unsigned int seed;
  19.  
  20.     /* Get optional hand size */
  21.     if (argc > 1)
  22.         if ((ncards = abs(atoi(argv[1])) % DECKSIZE) == 0)
  23.             ncards = DECKSIZE;
  24.  
  25.     /* Seed the random number generator */
  26.     seed = (unsigned int) time(NULL);
  27.     srand(seed);
  28.  
  29.      /* Shuffle */
  30.     deckp = 0;
  31.     while (deckp < ncards)
  32.     {
  33.         int num = rand() % DECKSIZE;
  34.         if (memchr(deck, num, deckp) == NULL)
  35.             deck[deckp++] = (char) num;
  36.     }
  37.  
  38.     /* Deal */
  39.     for (deckp = 0; deckp < ncards; ++deckp)
  40.     {
  41.         div_t card = div(deck[deckp], SUITSIZE);
  42.         printf(
  43.                "%c(%c)%c",
  44.                "A23456789TJQK"[card.rem],
  45.                "CDHS"[card.quot],
  46.                (deckp+1) % SUITSIZE ? ' ' : '\n'
  47.               );
  48.     }
  49.  
  50.     return 0;
  51. }
  52.  
  53. /* Output: */
  54. A(C) 6(S) 7(C) 9(C) 3(H) 6(C) 8(D) 3(C) 6(D) 5(D) 2(H) A(S) 4(H)
  55. 8(C) 8(H) 6(H) J(S) 7(S) Q(C) 2(C) Q(H) K(H) 4(C) 5(S) T(H) Q(S)
  56. 9(H) T(D) T(S) 9(D) K(C) 3(S) J(C) 5(C) T(C) K(S) 7(D) 2(D) 4(S)
  57. 8(S) 5(H) A(D) 7(H) 3(D) Q(D) A(H) 2(S) J(D) 9(S) K(D) J(H) 4(D)
  58.  
  59.